import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:landlore/consts.dart';

import '../customWidget/homePageRoomDisplayCard.dart';
import '../customWidget/titleTab.dart';
import '../dbUtil/databaseHelper.dart';
import '../model/orderVO.dart';

class HomePage extends StatefulWidget {
  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  //设置默认选中日期为:当前日期往前推10天(实际操作中需要选中的日期,月末和月初最多)
  int currentYear = DateTime.now().subtract(const Duration(days: 10)).year;
  int currentMonth = DateTime.now().subtract(const Duration(days: 10)).month;

  // final ScrollController _scrollController = ScrollController();

  List<OrderVO> roomList = [];

  int billoutCount = 0;
  int payoutCount = 0;

  int titleRankButtonFlag = 0;

  @override
  void initState() {
    // TODO: implement initState
    //设置为竖屏
    SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
    Consts().initalYearList();

    //初始化customerScrollView的Controller,用以监控是否下滑到尽头,用于更新数据
    // _scrollController.addListener(_scrollListener);
    _getRoomList();
    super.initState();
  }

  _getRoomList() async {
    DatabaseHelper dbHelper = DatabaseHelper.instance;
    List<OrderVO> resultData = await dbHelper.getHomePageRoom(
        currentYear, currentMonth, titleRankButtonFlag);

    int tempBill = 0;
    int tempPay = 0;
    resultData.forEach((data) {
      if (data.state == OrderState.BILL_OUT) {
        tempBill++;
      }
      if (data.checkState == 1) {
        tempPay++;
      }
    });

    setState(() {
      roomList = resultData;
      billoutCount = tempBill;
      payoutCount = tempPay;
    });
  }

  @override
  void dispose() {
    // _scrollController.removeListener(_scrollListener);
    // _scrollController.dispose();
    super.dispose();
  }

  // void _scrollListener() {
  //   if (_scrollController.position.atEdge &&
  //       _scrollController.position.pixels == 0) {
  //     // 已经滚动到顶部
  //     // 触发你的函数
  //     // setState(() {
  //     //   _getRoomList();
  //     // });
  //   }
  // }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        // controller: _scrollController,
        slivers: [
          SliverAppBar(
            expandedHeight: 280.h,
            // pinned: true,
            flexibleSpace: FlexibleSpaceBar(
              // title: Text('title'),
              background: TitleTab(
                callback: (selectedYear, selectedMonth) {
                  setState(() {
                    currentYear = selectedYear;
                    currentMonth = selectedMonth;
                    _getRoomList();
                  });
                },
                currentYear: currentYear,
                currentMonth: currentMonth,
                popCallback: () {
                  //返回刷新
                  _getRoomList();
                },
              ),
            ),
          ),
          SliverList(
            delegate: SliverChildBuilderDelegate(
              (context, index) {
                return Container(
                    decoration: BoxDecoration(
                        color: const Color(0xfff4a261),
                        image: DecorationImage(
                            image:
                                const AssetImage('assets/images/crossword.png'),
                            repeat: ImageRepeat.repeat,
                            colorFilter: ColorFilter.mode(
                                Colors.black.withOpacity(0.3),
                                BlendMode.srcIn))),
                    child: roomList.isEmpty
                        ? Center(
                            child: Text(
                              '还没有可用房源,点击 管理 添加房源',
                              style: TextStyle(
                                  fontFamily: '欢字卡通手书',
                                  fontSize: 50.sp,
                                  color: Colors.black),
                            ),
                          )
                        :
                        //第一行增加一个padding
                        index == 0
                            ? Column(
                                children: [
                                  Offstage(
                                    offstage: billoutCount == 0,
                                    child: Padding(
                                      padding: EdgeInsets.only(top: 25.h),
                                      child: Row(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        mainAxisAlignment:
                                            MainAxisAlignment.center,
                                        children: [
                                          CountLegend(
                                            color: const Color(0xfff07167),
                                            contentText: '已出单 : ',
                                            countingNum: billoutCount,
                                          ),
                                          CountLegend(
                                            color: Colors.green,
                                            contentText: '已付 : ',
                                            countingNum: payoutCount,
                                          ),
                                          SizedBox(
                                            width: 15.w,
                                          ),
                                          ElevatedButton(
                                              style: ElevatedButton.styleFrom(
                                                backgroundColor:
                                                    titleRankButtonFlag == 0
                                                        ? Colors.grey
                                                        : titleRankButtonFlag ==
                                                                1
                                                            ? Colors.green
                                                            : const Color(
                                                                0xfff07167), // 按钮的背景颜色
                                              ),
                                              onPressed: () {
                                                if (titleRankButtonFlag == 0) {
                                                  titleRankButtonFlag = 1;
                                                } else if (titleRankButtonFlag ==
                                                    1) {
                                                  titleRankButtonFlag = 2;
                                                } else {
                                                  titleRankButtonFlag = 0;
                                                }
                                                _getRoomList();
                                              },
                                              child: titleRankButtonFlag == 0
                                                  ? Text(
                                                      '默认排序',
                                                      style: TextStyle(
                                                          fontSize: 18.sp,
                                                          fontWeight:
                                                              FontWeight.bold),
                                                    )
                                                  : titleRankButtonFlag == 1
                                                      ? Text(
                                                          '置顶已付',
                                                          style: TextStyle(
                                                              fontSize: 18.sp,
                                                              fontWeight:
                                                                  FontWeight
                                                                      .bold),
                                                        )
                                                      : Text(
                                                          '置顶未付',
                                                          style: TextStyle(
                                                              fontSize: 18.sp,
                                                              fontWeight:
                                                                  FontWeight
                                                                      .bold),
                                                        ))
                                        ],
                                      ),
                                    ),
                                  ),
                                  Padding(
                                    padding: EdgeInsets.only(top: 20.h),
                                    child: HomePageRoomDisplayCard(
                                        orderVO: roomList[index],
                                        popCallback: () {
                                          //返回刷新
                                          _getRoomList();
                                        }),
                                  ),
                                ],
                              )
                            : HomePageRoomDisplayCard(
                                orderVO: roomList[index],
                                popCallback: () {
                                  //返回刷新
                                  _getRoomList();
                                })); // 自定义的帖子项
              },
              childCount: roomList.isEmpty ? 1 : roomList.length, // 假设有10条帖子
            ),
          ),
          SliverFillRemaining(
            hasScrollBody: false,
            child: Container(
                decoration: BoxDecoration(
                    color: const Color(0xfff4a261),
                    image: DecorationImage(
                        image: const AssetImage('assets/images/crossword.png'),
                        repeat: ImageRepeat.repeat,
                        colorFilter: ColorFilter.mode(
                            Colors.black.withOpacity(0.3), BlendMode.srcIn)))),
          )
        ],
      ), // 自定义的帖子列表
    );
  }
}

class CountLegend extends StatelessWidget {
  final Color color;
  final String contentText;
  final int countingNum;

  const CountLegend({
    super.key,
    required this.color,
    required this.contentText,
    required this.countingNum,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(top: 15.h, left: 5.w, right: 5.w),
      child: Row(
        children: [
          Container(
            width: 25.w,
            height: 25.w,
            decoration: BoxDecoration(
                color: color,
                border: Border.all(color: Colors.black, width: 2.w),
                borderRadius: BorderRadius.all(Radius.circular(25.r))),
          ),
          Text(
            contentText,
            style: TextStyle(fontSize: 18.sp, fontWeight: FontWeight.w600),
          ),
          Text(
            '$countingNum',
            style: TextStyle(fontSize: 20.sp, fontWeight: FontWeight.w900),
          )
        ],
      ),
    );
  }
}
